package com.jeecms.wicool.action.lottery;

import static com.jeecms.common.page.SimplePage.cpn;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jeecms.cms.manager.main.CmsLogMng;
import com.jeecms.cms.web.CmsUtils;
import com.jeecms.cms.web.WebErrors;
import com.jeecms.common.page.Pagination;
import com.jeecms.common.web.CookieUtils;
import com.jeecms.wicool.entity.lottery.Sn;
import com.jeecms.wicool.entity.util.Dictionary2;
import com.jeecms.wicool.manager.lottery.SnMng;
import com.jeecms.wicool.manager.shops.WiShopInfoMng;
import com.jeecms.wicool.manager.util.DictionaryMng;
import com.jeecms.wicool.util.ConstantUtil;
import com.jeecms.wicool.util.SecurityUtil;

@Controller
public class SnAct {
	private static final Logger log = LoggerFactory.getLogger(SnAct.class);

	@RequestMapping("/sn/v_list.do")
	public String list(String prizeName,Integer status,String sn_str,Integer pageNo,HttpServletRequest request, ModelMap model) {
		Pagination pagination = manager.getPage( prizeName, status, sn_str,cpn(pageNo),
				CookieUtils.getPageSize(request),CmsUtils.getUser(request));
		model.addAttribute("pagination", pagination);
		List<Sn> listSn=(List<Sn>)pagination.getList();
		List<Dictionary2> listSnStatus=DicMng.getList("sn_status");
		Map<String,String> map = new HashMap<String,String>();
		 for(Dictionary2 d : listSnStatus){
			 map.put(d.getDicCode().toString(), d.getDicName());
		 } 
		 for(Sn p : listSn){
			 if(map.containsKey(p.getStatus().toString())){
				 p.setStatusName(map.get(p.getStatus().toString()));
			 }
			 try {
				p.setSn(SecurityUtil.aesDecode(p.getSn(), ConstantUtil.key));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		 }
		 model.addAttribute("pagination", pagination);
		 model.addAttribute("listSnStatus", listSnStatus);
		model.addAttribute("prizeName",prizeName);
		model.addAttribute("status",status);
		model.addAttribute("sn_str",sn_str);
		return "lottery/list_sn";
	}
	
	@RequestMapping("/sn/v_view.do")
	public String view(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Sn sn = manager.findById(id);
		try {
			sn.setStatusName(DicMng.findByDicCode("sn_status", Short.parseShort(Integer.toString(sn.getStatus()))).getDicName());
			
			sn.setSn(SecurityUtil.aesDecode(sn.getSn(), ConstantUtil.key));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		model.addAttribute("sn",sn);
		
		return "lottery/view_sn";
	}
	
	@RequestMapping("/sn/v_cash.do")
	public String cash(Integer id, String prizeName,Integer status,String sn_str,HttpServletRequest request, ModelMap model) {
		WebErrors errors = validateEdit(id, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Sn sn = manager.findById(id);
		try {
			sn.setStatusName(DicMng.findByDicCode("sn_status", Short.parseShort(Integer.toString(sn.getStatus()))).getDicName());
			
			sn.setSn(SecurityUtil.aesDecode(sn.getSn(), ConstantUtil.key));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		model.addAttribute("sn",sn);
		return "lottery/cash_sn";
	}
	@RequestMapping("/sn/o_update.do")
	public String update(Sn bean,String userSn,Integer id,String prizeName,Integer status,String sn_str,Integer pageNo,HttpServletRequest request,ModelMap model) throws Exception {
		WebErrors errors = validateUpdate(bean.getId(), request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		Sn sn=manager.findById(bean.getId());
		try {
			if(sn.getSn().equals(SecurityUtil.aesEncode(userSn, ConstantUtil.key))){
			SimpleDateFormat simpleTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String dateTime = simpleTime.format(new Date());
			Timestamp t = Timestamp.valueOf(dateTime);
			sn.setUpdateTime(t);
			sn.setSendTime(t.toString());
			sn.setStatus(2);
			
			sn.setPhone(bean.getPhone());
			sn.setWeixin(bean.getWeixin());
			
			sn=manager.update(sn);
			model.addAttribute("message", "global.success");
			}else{
			model.addAttribute("message", "SN码有误，不能兑换成功！");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list(prizeName, status, SecurityUtil.aesDecode(sn.getSn(), ConstantUtil.key), pageNo, request, model);
	}
	private WebErrors validateEdit(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		return errors;
	}

	private WebErrors validateUpdate(Integer id, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		if (vldExist(id, errors)) {
			return errors;
		}
		// TODO 验证是否为管理员，管理员不允许修改。
		return errors;
	}
	private WebErrors validateDelete(Integer[] ids, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		errors.ifEmpty(ids, "ids");
		for (Integer id : ids) {
			vldExist(id, errors);
		}
		return errors;
	}

	private boolean vldExist(Integer id, WebErrors errors) {
		if (errors.ifNull(id, "id")) {
			return true;
		}
		Sn entity = manager.findById(id);
		if (errors.ifNotExist(entity, Sn.class, id)) {
			return true;
		}
		return false;
	}
	@Autowired
	private SnMng manager;
	@Autowired
	private CmsLogMng cmsLogMng;
	@Autowired
	private DictionaryMng DicMng;
	@Autowired
	private WiShopInfoMng shopMng;
}
